package git.soulbgm;

import git.soulbgm.listener.TcpChannelFutureListener;
import git.soulbgm.socket.TcpClient;
import git.soulbgm.socket.TcpClientHandle;
import git.soulbgm.utils.ChannelUtil;
import io.netty.channel.ChannelFuture;
import java.util.Scanner;

/**
 * 程序入口
 *
 * @author SoulBGM
 * @date 2021-03-29
 */
public class TcpClientApplication {

    public static void main(String[] args) throws InterruptedException {
        TcpClient tcpClient = TcpClient.getClient();
        tcpClient.start(new TcpClientHandle());
        doConnect(tcpClient, "10.1.7.202", 9191);
        doConnect(tcpClient, "10.1.7.202", 9192);
        doConnect(tcpClient, "10.1.7.202", 9193);
        Scanner scanner = new Scanner(System.in);
        Thread.sleep(2000);
        while (true) {
            System.out.print("发送IP: ");
            String ip = scanner.nextLine();
            System.out.print("发送端口: ");
            int port = Integer.parseInt(scanner.nextLine());
            ChannelFuture future = ChannelUtil.getChannelFuture(ip, port);
            if (future == null) {
                System.out.println("没有该IP的通道");
                continue;
            }
            System.out.print("发送数据(16进制): ");
            String hex = scanner.nextLine();
            byte[] bytes = ChannelUtil.hexStrToBytes(hex);
            ChannelUtil.tcpSendMsg(future.channel(), bytes);
        }
    }

    private static ChannelFuture doConnect(TcpClient tcpClient, String host, int port) {
        return tcpClient.connect(host, port, new TcpChannelFutureListener(host, port));
    }

}
